package com.justgame.project.service.system.controller;

import com.justgame.mq.client.constant.SystemQueueConstant;
import com.justgame.mq.client.service.RabbitMqSendService;
import com.justgame.project.base.annotation.ProtectAccess;
import com.justgame.project.cloud.common.constant.Regex;
import com.justgame.project.cloud.common.constant.Result;
import com.justgame.project.cloud.common.exception.Exc;
import com.justgame.project.cloud.common.util.RedisDistributedLock;
import com.justgame.project.cloud.common.util.RedisUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/sys/verification")
@Api("真实信息校验接口")
public class VerificationController {

    private final RedisUtils redisUtils;
    private final RedisDistributedLock lock;
    private final RabbitMqSendService rabbitMqSendService;

    @GetMapping("/phone-number")
    @ProtectAccess(60L)
    public Result<?> verificationPhoneNumber(String phoneNumber) throws InterruptedException {
        String requestId = UUID.randomUUID().toString();
        try{
            if (lock.tryLock("LOCK:"+phoneNumber,requestId,1000,1000,50)){
                Assert.hasLength(phoneNumber,"必须提供手机号");
                Assert.isTrue(Regex.isPhone(phoneNumber),"手机号格式不正确");
                String limit = redisUtils.get("LIMIT:"+phoneNumber);
                Assert.isTrue(limit == null || Integer.parseInt(limit) < 10,"发送短信操作频繁，请稍后再试");
                if (limit == null){
                    redisUtils.set("LIMIT:"+phoneNumber,1);
                }else{
                    redisUtils.increment(phoneNumber);
                }
                rabbitMqSendService.sendMsg(SystemQueueConstant.SMS,phoneNumber);
                return Result.ok("验证码已发送");
            }
        }catch (IllegalArgumentException e){
            throw e;
        }finally {
            lock.releaseLock("LOCK:"+phoneNumber,requestId);
        }
        return Result.ok();
    }

}
